package com.ysh.springcaptchademo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.ysh.springcaptchademo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaTestController {

    @Autowired
    private CaptchaProperties captchaProperties;
    private final static long VALID_TIME = 30 * 60 * 1000L;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        long start = System.currentTimeMillis();
        response.setContentType("image/jpeg");
//        response.setCharacterEncoding("utf-8");
        try {
            //生成验证码
            //定义图形验证码的长和宽
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
            String code = lineCaptcha.getCode();
            session.setAttribute(captchaProperties.getSession().getKey(), code);
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        System.out.println("getCaptcha cost time: "+(end - start)+"ms");
    }

    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session) {
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }
        //验证 验证码
        String code = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date data = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if (captcha.equalsIgnoreCase(code)&&data != null
                && System.currentTimeMillis() - data.getTime() < VALID_TIME) {
            return true;
        }
        return false;
    }


}





